using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Zombie : MonoBehaviour, IInteractable
{
    public Vector3 direction; //移动方向
    public float speed;//速度
    private float currentSpeed;//当前速度
    private Animator animator;
    private Character character;
    public GameObject lostHead;//断头预制体
    private Transform head;//断头位置
    private bool isLostHead;//是否已经断头
    bool attack;

    private void Start()
    {
        animator = GetComponent<Animator>();
        character = GetComponent<Character>();
        head = transform.Find("Head");
        currentSpeed = speed;
    }

    void Update()
    {
        transform.position += direction * currentSpeed * Time.deltaTime;

        //断头
        if (character.currentHealth <= 50 && isLostHead == false)
        {
            isLostHead = true;
            Instantiate(lostHead, head.position, Quaternion.identity);
            animator.SetBool("headless", true);
        }
    }

    //进入触发器 
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("Plant")) return;
        animator.SetBool("attack", true);
        currentSpeed = 0;

        attack = true;
        //重复执行
        InvokeRepeating("PlayEatSFX", 0, 1f);
    }

    //离开触发器
    private void OnTriggerExit2D(Collider2D other)
    {
        if (!other.CompareTag("Plant")) return;

        animator.SetBool("attack", false);
        currentSpeed = speed;
        attack = false;
    }

    public void OnDie()
    {
        currentSpeed = 0;
        animator.SetBool("die", true);
        GetComponent<Collider2D>().enabled = false;
        Destroy(gameObject, 2f);

        GenerateZombies.Instance.ZombieDied(gameObject);
    }

    private void PlayEatSFX()
    {
        if (attack == false) return;
        //随机播放
        int index = UnityEngine.Random.Range(0, 2);
        switch (index)
        {
            case 0:
                AudioManager.Instance.PlaySFX("吃植物1");
                break;
            default:
                AudioManager.Instance.PlaySFX("吃植物2");
                break;
        }
        
    }
}
